import logging

import pymysql

from common.logging_use import log01
from config import HOST, PORT, USER, PASSWORD, DATABASE


class DBUtil():
    log01
    conn = None

    # 创建链接
    @classmethod
    def __create_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host=HOST, port=PORT, user=USER, password=PASSWORD,
                                       database=DATABASE, charset="utf8")
        return cls.conn

    # 关闭链接
    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    # 查询一个结果
    @classmethod
    def select_one(cls, sql):
        cur = None
        one = None
        try:
            # 创建链接
            cls.conn = cls.__create_conn()
            # 创建游标
            cur = cls.conn.cursor()
            # 执行sql
            cur.execute(sql)
            # 获取结果
            one = cur.fetchone()
        except Exception as err:
            # print("错误信息是：", err)
            logging.info(err)
        finally:
            # 关闭游标
            cur.close()
            # 关闭链接
            cls.__close_conn()
            return one

    # 定义增删改
    @classmethod
    def uid_db(cls, sql):
        cur = None
        rows = None
        try:
            # 创建链接
            cls.conn = cls.__create_conn()
            # 创建游标
            cur = cls.conn.cursor()
            # 执行sql
            cur.execute(sql)
            # 成功 - 提交
            cls.conn.commit()
            # 拿到受影响行数
            rows = cls.conn.affected_rows()
        except Exception as err:
            # print("错误信息是：", err)
            logging.info(err)
            # 失败 - 回滚
            cls.conn.rollback()
        finally:
            # 关闭游标
            cur.close()
            # 关闭链接
            cls.__close_conn()
            return f"受影响的行数是：{rows}"


if __name__ == '__main__':
    # a=DBUtil.select_one("select * from t_book;")
    # print(a)
    # DBUtil.uid_db("update t_book set `read` = 100 where id = 3;")
    # DBUtil.uid_db("insert into t_book(id,title,pub_date,`read`) values(1829588,'《Python从放弃到放弃》','2040-01-01',50);")
    # DBUtil.uid_db("update t_book set comment = 250 where id = 1829588;")
    # DBUtil.uid_db("delete from t_book where id=18484848;")
    # b=DBUtil.select_one("select * from t_book where id = 1829588;")
    # print(b)
    c = DBUtil.select_one("select * from t_book where id = 18484848;")
    print(c)







